<%@page import="com.farm.parameter.FarmParameterService"%>
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="/view/conf/farmtag.tld" prefix="PF"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<!-- 批量上传附件 -->
<script src="text/lib/fileUpload/jquery.ui.widget.js"></script>
<script src="text/lib/fileUpload/jquery.iframe-transport.js"></script>
<script src="text/lib/fileUpload/jquery.fileupload.js"></script>
<link href="text/lib/fileUpload/jquery.fileupload.css" rel="stylesheet">
<style>
<!--
.bar {
	height: 18px;
	background: green;
}
.WfsUploadDropBox {
	border: 1px dashed #888;
	background-color: #f4f4f4;
}
.WfsUploadDropBox.active {
	border: 1px solid #656464;
}
-->
</style>
<!-- Modal -->
<div class="modal fade" id="uploadModalId" tabindex="-1" role="dialog"
	aria-labelledby="myModalLabel">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"
					aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
				<h4 class="modal-title" id="myModalLabel">上传文件</h4>
			</div>
			<div class="modal-body" id="uploadModalContentId"> 
				<div class="btn-group btn-group-justified" role="group"
					aria-label="Justified button group with nested dropdown">
					<span class="btn btn-info fileinput-button" role="button"> <span>批量上传文件</span> 
						<span id="html5uploadProsess"></span> <input id="fileupload"
						type="file" name="file" multiple>
					</span>
					<!--  -->
					<a data-toggle="modal" data-target="#base64fileWinId"
						class="btn btn-warning" role="button">提交base64编码图片</a>
				</div>
				<div class="progress" id="fileUploadProgressBarId" style="margin: 20px;margin-left: 0px;margin-right: 0px;display: none;">  
				  <div id="progressCpercentTitleId" class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
				    0%
				  </div> 
				</div>
				<div id="fileQueue"  style="text-align: left;">
					<div class="center-block text-center blocktip-title WfsUploadDropBox">
						<i class="glyphicon glyphicon-paperclip"></i> 将文件<b>拖入此框</b>内(支持firfox,chrome)或通过点击<b>上方按钮</b>上传
					</div>
				</div>
				<div class="row" id="fileListId" style="padding: 20px;">
					<!-- 文件列表 -->
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
				<button type="button" onclick="submitUploadFile();" class="btn btn-primary">提交</button>
			</div>
		</div>
	</div>
</div>
<!-- base64圖片提交窗口 -->
<div class="modal fade" id="base64fileWinId" tabindex="-9999"
	role="dialog" aria-labelledby="myModalLabel">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"
					aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
				<h4 class="modal-title" id="myModalLabel">录入base64编码的图片</h4>
			</div>
			<div class="modal-body">
				<input id="base64FileName" type="text" class="form-control"
					placeholder="录入文件名称"> <br />
				<textarea id="base64FileCode" class="form-control"
					placeholder="请录入base64编码文件" style="width: 100%; height: 200px;"></textarea>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
				<button id="base64SubmitButId" type="button" class="btn btn-primary">提交</button>
			</div>
		</div>
	</div>
</div>
<script type="text/javascript">
	//单个文件大小
	var maxSize = parseInt("${config_doc_upload_length_max}");
	var currentUserId='${USEROBJ.id}';
	//单次上传文件数量
	var maxFileNum = 1;
	//打开上传窗口
	function OpenUploadWin() {
		if(!currentUserId){
			window.location="login/PubLogin.html";
		}
		$('#uploadModalId').modal('show');
	}
	$(function() {
		var maxSizeTitle = (maxSize / 1024 / 1024).toFixed(2);
		$('#fileupload')
				.fileupload(
						{
							url : "upload/general.do",
							dataType : 'json',
							change : function(e, data) {
								$('#fileListId').html('');
								var isOK= updateFileValidate(data.files)
								return isOK;
							}, 
							done : function(e, data) {
								var url = data.result.url;
								var state = data.result.STATE;
								var message = data.result.MESSAGE;
								var id = data.result.id;
								var fileName = data.result.fileName;
								if (state == 1) {
									showErrorMessage(message)
									return;
								}
								addFileNode('download/Pubicon.do?id=' + id,
										decodeURIComponent(fileName), id,
										"fileListId");
							},
							progressall : function(e, data) {
								var progress = parseInt(data.loaded
										/ data.total * 100, 10);
								loadFileProcess("上传",progress,'client');
								if (progress == 100) {
									setFileProcessBar(false);
									loadRemoteProcess(true);
								} else {
									setFileProcessBar(true);
								}
							}
						});
		$('#base64SubmitButId').click(function() {
			submitBase64Imgs();
		});
	});
	//添加一个界面文件元素
	function addFileNode(imgUrl, fileName, fileId, domBoxId) {
		$('.blocktip-title').hide();
		var html = '<div class="col-sm-12 file-block-box"   id="file_'+fileId+'">';
		html = html + '		<div class="stream-item" >';
		html = html + '				<div class="media">';
		html = html + '					<div class="pull-left">';
		html = html + '						<img  alt="'+fileName+'" src="'+imgUrl+'">';
		html = html + '					</div>';
		html = html + '					<div class="media-body" >';
		html = html
				+ '<i onclick="removeFile(\''
				+ fileId
				+ '\');" title="删除临时文件" class="glyphicon glyphicon-remove pull-right" ></i>';
		html = html + '						<div class="file-title" >' + fileName + '</div>';
		html = html + '					</div>';
		html = html + '				</div>';
		html = html + '		</div>';
		html = html
				+ '<input type="hidden" name="fileId" value="'+fileId+'" /></div>';
		$('#' + domBoxId).append(html);
	}
	//删除一个文件
	function removeFile(fileId) {
		$.post('document/del.do', {
			id : fileId
		}, function(data) {
			if (data.STATE == 0) {
				hideFileBox(fileId);
			} else {
				showErrorMessage(data.MESSAGE);
			}
		}, 'json');
	}
	//刪除一個附件圖標元素
	function hideFileBox(fileid) {
		$("#file_" + fileid).remove();
		//判断附件是否上传
		if ($("input[name='fileId']").length == 0) {
			$('.blocktip-title').show();
		}
	}
	//提交base64位编码图片
	function submitBase64Imgs() {
		if (!isnull($('#base64FileName').val())
				&& !isnull($('#base64FileCode').val())) {
			$.post('upload/base64img.do', {
				'base64' : $('#base64FileCode').val(),
				'filename' : $('#base64FileName').val()
			}, function(data) {
				$('#base64fileWinId').modal('hide');
				$('#base64FileCode').val('');
				$('#base64FileName').val('');
				var url = data.url;
				var state = data.STATE;
				var message = data.MESSAGE;
				var id = data.id;
				var fileName = data.fileName;
				if (state == 1) {
					showErrorMessage(message)
					return;
				}
				addFileNode('download/Pubicon.do?id=' + id,
						decodeURIComponent(fileName), id, "fileListId");
			}, 'json');
		} else {
			alert("请录入base64文件名称和编码!");
		}
	}
	//顯示错误消息弹框
	function showErrorMessage(message) {
		alert(message);
	}
	//提交上传的文件
	function submitUploadFile() {
		$('#fileListId input').each(function(i, obj) {
			submitFile($(obj).val());
		});
	}
	//提交一个文件为持久状态
	function submitFile(fileId) {
		$.post('document/submit.do', {
			id : fileId
		}, function(data) {
			if (data.STATE == 0) {
				//跳转到文件信息页面
				window.location="document/view.do?fileid="+fileId;
			} else {
				showErrorMessage(data.MESSAGE);
			}
		}, 'json');
	}
	var isLoadRemotProecess=false;
	//检查远程进度
	function loadRemoteProcess(state){
		isLoadRemotProecess=state;
		if(state){
			setFileProcessBar(true);
			setTimeout("doloadRemoteProcess()",1000); //延迟1秒
		}
	}
	//加载远程进度
	function doloadRemoteProcess(){
		$.post("upload/PubUploadProcess.do",{},function(flag){ 
			if(flag.STATE==0){
				loadFileProcess("服务器端处理文件",flag.process,'server');
				if(flag.process>99){
					isLoadRemotProecess=false;
					setFileProcessBar(false);
				}
				if(isLoadRemotProecess){
					setTimeout("doloadRemoteProcess()",1000); //延迟1秒	
				}
			}else{
				alert(flag.MESSAGE);
			} 
		},'json');
	}
	//显示进度条（控制显示或隐藏）
	function setFileProcessBar(flag){
		if(flag){
			$('#fileUploadProgressBarId').show();
		}else{
			$('#fileUploadProgressBarId').hide();
		}
	}
	//显示进度条(信息)
	function loadFileProcess(title,num,type){
		var allnum=0;
		if(type=='server'){
			allnum=50+num/2; 
		}
		if(type=='client'){
			allnum=num/2;
		}
		$('#progressCpercentTitleId').text(title+":"+allnum + '%');
		$('#progressCpercentTitleId').css('width',allnum+'%');
	}
	//检查上传文件，返回值为是否允许上传
	function updateFileValidate(files) {
		if (files.length > maxFileNum) {
			alert("单次上传文件数量不能大于" + maxFileNum + "个!");
			return false;
		}
		var isOK = true;
		$(files).each(function(i, obj) {
			if (obj.size > maxSize) {
				alert("文件" + obj.name + "超大,请检查文件大小不能大于" + maxSizeTitle + "m");
				isOK = false;
			}
		});
		return isOK;
	}
</script>
<script>
	$(function() {
		$('body').bind('drop', function(ev) {
			ev.stopPropagation();
			ev.preventDefault();
		});
		initDropBox();
	});
	//初始化拖拽框
	function initDropBox(){
		var uploadDrop = document.getElementById('uploadModalContentId');
		uploadDrop.addEventListener('dragover', function(event) {
			$('.WfsUploadDropBox').addClass("active");
			event.preventDefault();
		});
		uploadDrop.addEventListener('dragenter', function(event) {
			event.preventDefault();
		});
		uploadDrop.addEventListener('dragleave', function(event) {
			$('.WfsUploadDropBox').removeClass("active");
			event.preventDefault();
		});
		uploadDrop.addEventListener('drop', function(event) {
			$('.WfsUploadDropBox').removeClass("active");
			event.preventDefault();
			var fileList = Array.from(event.dataTransfer.files);
			var uploadAble = updateFileValidate(fileList);
			$('#fileListId').html('');
			if (uploadAble) {
				for (var i = 0; i < fileList.length; i++) {
					sendFileByXHR('upload/general.do', fileList[i]);
				}
			}
		});
	}
	//上传拖拽文件
	function sendFileByXHR(url, fielObj) {
		var xhr = new XMLHttpRequest();
		xhr.upload.onprogress = function(event) {
			var progress = parseInt(event.loaded / event.total * 100, 10);
			setFileProcessBar(true)
			if (progress == 100) {
				setFileProcessBar(false);
				loadRemoteProcess(true);
			} else {
				setFileProcessBar(true);
			}
			loadFileProcess("上传",progress,'client');
		}
		xhr.onreadystatechange = function() {
			if (xhr.status === 200 && xhr.readyState === 4) {
				var jsonObject = JSON.parse(xhr.responseText, null);
				addFileNode('download/Pubicon.do?id=' + jsonObject.id,
						decodeURIComponent(jsonObject.fileName), jsonObject.id,
						"fileListId");
			}
		}
		xhr.onabort = function(event) {
			//终止
			console.log('abort');
		}
		xhr.onerror = function(event) {
			console.log('error');
			showErrorMessage('xhr.onerror-error');
		}
		var data = new FormData();
		data.append("file", fielObj);
		xhr.open('POST', url, true);
		xhr.send(data);
	}
</script>